import QRCode from "qrcode";
import store from "@/store";
import { ElMessageBox } from "element-plus";
import router from "@/router/index.js";
import { provinceAndCityDataPlus, CodeToText } from "element-china-area-data";

const provinceAndCityData = provinceAndCityDataPlus;

for (let i = 0; i < provinceAndCityDataPlus.length; i++) {
  if (
    ["110000", "120000", "310000", "500000"].includes(
      provinceAndCityData[i].value
    )
  ) {
    provinceAndCityData[i].children = provinceAndCityData[i].children.splice(
      0,
      1
    );
  }
}
const ReqApi = "https://i53w431926.zicp.fun";

const osshost =
  process.env.VUE_APP_ENV != "production"
    ? "http://alioss.linshibin.com/"
    : "https://oss.oact.net/";

/**
 * @name  默认请求分页参数
 */
const pageSize = 20;
const getQuerySize = (rawH = 60, removeH = 300) => {
  const wrapH = window.innerHeight - removeH;
  return Math.floor(wrapH / rawH) || 10;
};

const download = (url, fileName) => {
  const elink = document.createElement("a");
  elink.href = url;
  elink.setAttribute("download", fileName);
  elink.style.display = "none";
  document.body.appendChild(elink);
  setTimeout(() => {
    elink.click();
    document.body.removeChild(elink);
  }, 66);
}
/**
 * @name  二维码生成
 *
 */
const qrcode = (host = "www.baidu.com", obj) => {
  let w = 250;
  let h = 250;
  if (obj) {
    w = obj.w;
    h = obj.h;
  }
  return (QRCode as any).toDataURL(host, {
    width: w,
    height: h,
    margin: 1,
  });
};

/**
 * @name  OSS服务器图片
 */
const imgUrlFilter = (url, w = 750, type = "img") => {
  let link = url;

  if (link != "" && link != undefined && link != null) {
    if (link.indexOf("http") == -1) {
      if (type == "video") {
        link = `${osshost + link}`;
      } else {
        link = `${osshost + link}?x-oss-process=image/resize,w_${w || 100
          }/format,jpg/quality,Q_80`;
      }
    }
  }

  return link;
};

/**
 * @name  for-in-深拷贝对象
 */
const forinCopy = (obj) => {
  const result = Array.isArray(obj) ? [] : {};
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      if (typeof obj[key] === "object" && obj[key] !== null) {
        //递归复制
        result[key] = forinCopy(obj[key]);
      } else result[key] = obj[key];
    }
  }
  return result;
};

/**
 * @name 对象深拷贝
 */
const copy = (obj, type = "json") => {
  let robj = {};
  if (type === "json") {
    robj = JSON.parse(JSON.stringify(obj));
  } else {
    // const result = Array.isArray(obj) ? [] : {};
    // for (const key in obj) {
    //   if (Object.prototype.hasOwnProperty.call(obj, key)) {
    //     if (typeof obj[key] === "object" && obj[key] !== null) {
    //       //递归复制
    //       result[key] = forinCopy(obj[key]);
    //     } else result[key] = obj[key];
    //   }
    // }
    robj = forinCopy(obj);
  }
  return robj;
};

/**
 * @name 设置最小高度
 */

const majorHtmlBoxH = (reduceH = 310, isMin = false) => {
  const height = document.body.clientHeight;
  return isMin
    ? {
      minHeight: height - reduceH + "px",
    }
    : { height: height - reduceH + "px" };
};

/**
 * @name 重置对象，将值处理为空
 */

const dataReset = (_data, type = "obj") => {
  let data = JSON.parse(JSON.stringify(_data));
  if (type === "obj") {
    for (const k in data) {
      if (typeof data[k] === "object") {
        if (Array.isArray(data[k])) {
          return;
        } else data[k] = "";
      } else data[k] = "";
    }
  } else if (type === "json") {
    data = "";
  }
  _data = data;
  return data;
};

/**
 * @name 金额格式化方法：加￥和2位小数点
 */

const fprice = (val, pre = false) => {
  val = Number(val);
  if (isNaN(val)) val = 0;
  return (pre ? "￥" : "") + val.toFixed(2);
};

/**
 * @name 会员等级判定提示方法
 */

const members = (params: any) => {
  ElMessageBox({
    title: "提示", //MessageBox 标题
    message: params.Data.Msg, //MessageBox 消息正文内容
    confirmButtonText: "去升级", //确定按钮的文本内容
    cancelButtonText: "关闭", //取消按钮的文本内容
    showCancelButton: true, //是否显示取消按钮
    closeOnClickModal: false, //是否可通过点击遮罩关闭
    customClass: params.del == 0 ? "customClassDel" : "customClassReset",
    type: "warning", //消息类型，用于显示图标
  }).then((e) => {
    router.push({ path: "/upgrade" });
  });
};

/**
 * @name 验证用户权限接口
 */

const checkUserAuth = (
  FeatureKey = "CanViewVoteLog",
  success = () => { },
  IntValue = 0,
  IsInt = false,
  error = () => { }
) => {
  store
    .dispatch("user/AuthUserGroupFeature", { FeatureKey, IntValue, IsInt })
    .then((res) => {
      if (res.Code === 1) {
        if (res.Data.NeedUpgrade) {
          members(res);
          error();
        } else {
          success();
        }
      } else {
        error();
      }
    })
    .catch(() => {
      error();
    });
};

/**
 * @name Base64ToBlob
 */

const imageBase64ToBlob = (urlData, type = "image/jpeg") => {
  try {
    const arr = urlData.split(",");
    const mime = arr[0].match(/:(.*?);/)[1] || type;
    // 去掉url的头，并转化为byte
    const bytes = window.atob(arr[1]);
    // 处理异常,将ascii码小于0的转换为大于0
    const ab = new ArrayBuffer(bytes.length);
    // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
    const ia = new Uint8Array(ab);

    for (let i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i);
    }

    return new Blob([ab], {
      type: mime,
    });
  } catch (e) {
    const ab = new ArrayBuffer(0);
    return new Blob([ab], {
      type: type,
    });
  }
};

/**
 * @name 通用窗口提示
 */

const elMessageTip = (params1: any) => {
  const params: any = Object.assign(
    {
      title: "提示",
      text: "是否确认删除？",
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      del: 1,
      no() { },
      ok() { },
    },
    params1
  );
  ElMessageBox({
    title: params.title, //MessageBox 标题
    message: params.text, //MessageBox 消息正文内容
    confirmButtonText: params.confirmButtonText, //确定按钮的文本内容
    cancelButtonText: params.cancelButtonText, //取消按钮的文本内容
    showCancelButton: true, // 是否显示取消按钮
    closeOnClickModal: false, // 是否可通过点击遮罩关闭
    customClass: params.del == 0 ? "customClassDel" : "customClassReset",
    type: "warning", //消息类型，用于显示图标
  })
    .then((e) => {
      params.ok(e);
    })
    .catch((e) => {
      params.no(e);
    });
};

/**
 * @name 获取地址栏上的参数对象
 */

const parseQuery = () => {
  const query = location.search.substr(1);
  const reg = /([^=&\s]+)[=\s]*([^&\s]*)/g;
  const obj: any = {};
  while (reg.exec(query)) {
    obj[RegExp.$1] = RegExp.$2;
  }
  return obj;
};

/**
 * @name 日期格式方法-实列化
 */

const formatDate = (date, fmt) => {
  if (!date) {
    return null;
  }
  if (typeof date === "string") {
    date = new Date(date.replace(/-/g, "/"));
  }
  if (typeof date === "number") {
    date = new Date(date);
  }
  if (fmt === undefined) {
    return Number(date);
  } else {
    const o = {
      "M+": date.getMonth() + 1,
      "D+": date.getDate(),
      "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
      "H+": date.getHours(),
      "m+": date.getMinutes(),
      "s+": date.getSeconds(),
      "q+": Math.floor((date.getMonth() + 3) / 3),
      S: date.getMilliseconds(),
    };
    const week = {
      "0": "\u65e5",
      "1": "\u4e00",
      "2": "\u4e8c",
      "3": "\u4e09",
      "4": "\u56db",
      "5": "\u4e94",
      "6": "\u516d",
    };
    if (/(Y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    }
    if (/(E+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (RegExp.$1.length > 1
          ? RegExp.$1.length > 2
            ? "\u661f\u671f"
            : "\u5468"
          : "") + week[date.getDay() + ""]
      );
    }
    for (const k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
      }
    }
    return fmt;
  }
};

/**
 *  @name 日期格式方法-带时区
 */
const fDateZone = (date, flag = "YYYY-MM-DD HH:mm:ss") => {
  const endDate = formatDate(new Date(date), flag);
  return endDate.replace(/\s+/g, "T") + "+08:00";
};

/**
 * @name 日起格式方法qq
 */

const fDate = (date, flag = "YYYY-MM-DD HH:mm:ss") => {
  return formatDate(new Date(date), flag);
};

const formatTime = (date, flag = "YYYYMMDDHHmmss") => {
  return formatDate(new Date(date), flag);
};

/**
 * @name 获取7天前的时间
 */

const get7Day = () => {
  const oneweekdate = new Date(new Date().getTime() - 6 * 24 * 3600 * 1000);
  const y = oneweekdate.getFullYear();
  const m = oneweekdate.getMonth() + 1;
  const d = oneweekdate.getDate();
  return y + "-" + (m > 9 ? m : "0" + m) + "-" + (d > 9 ? d : "0" + d);
};

/**
 * @name 刷新预览手机模板窗口事件
 */
const previewLoading = () => {
  store.commit("PREVIEWLOAD", false);
  setTimeout(() => store.commit("PREVIEWLOAD", true), 1000);
};

const previewSetUp = () => {
  store.commit("commitSave", {
    key: "previewSetUp",
    data: false,
  });
  setTimeout(() => {
    store.commit("commitSave", {
      key: "previewSetUp",
      data: true,
    });
  }, 100);
};

/**
 * @name 基础提示弹窗
 */
const baseMsg = (text = "", success = true) => {
  store.commit("commitSave", {
    key: "msgText",
    data: text,
  });
  store.commit("commitSave", {
    key: "msgSuccess",
    data: Boolean(success),
  });
};

/**
 * @name 活动设置里面的接口响应成功，消息处理提示
 */

const resMsg = (res, ok, no) => {
  const msgsing = res.msgsing ? res.msgsing : "保存成功";
  if (res.code === 1) {
    const prevloading = res.loading ? res.loading : "";
    store.commit("commitSave", {
      key: "prevloading",
      data: prevloading,
    });
    store.commit("commitSave", {
      key: "ad",
      data: res.ad == 1 ? 1 : 0,
    });
    baseMsg(msgsing);
    previewLoading();
    if (typeof ok === "function") ok();
  } else {
    if (typeof no === "function") no();
  }
};

/**
 * 页面自适应缩放
 * 参数：要缩放的盒子dom
 * 未使用
 */
const pageAdaptiveScaling = (boxDom) => {
  function adaptation() {
    const w = document.body.clientWidth;
    const h = document.body.clientHeight;
    const nw = 1920;
    const nh = 1080;
    let left, top, scale;
    if (w / h > nw / nh) {
      scale = h / nh;
      top = 0;
      left = (w - nw * scale) / 2;
    } else {
      scale = w / nw;
      left = 0;
      // 居中
      // top = (h - nh * scale) / 2;
      top = 0;
    }
    boxDom.setAttribute(
      "style",
      `transform-origin: 0 0;
        transform: scale(${scale},${scale});
        left:${left}px;
        top:${top}px;`
    );
  }
  window.addEventListener("load", adaptation);
  window.addEventListener("resize", adaptation);
  // 禁用按住ctrl+鼠标缩放页面
  window.addEventListener(
    "mousewheel",
    function (event: any) {
      if (event.ctrlKey === true || event.metaKey) {
        event.preventDefault();
      }
    },
    { passive: false }
  );
  //firefox
  window.addEventListener(
    "DOMMouseScroll",
    function (event: any) {
      if (event.ctrlKey === true || event.metaKey) {
        event.preventDefault();
      }
    },
    { passive: false }
  );
};

const ParseData = (data) => {
  let str = "";
  for (let key in data) {
    str += [key] + "=" + data[key] + "&";
  }
  str = str.slice(0, str.length - 1);
  return str

}

const LocationHref = (url, data) => {
  location.href = ReqApi + url + "?" + ParseData(data);
}


export {
  CodeToText,
  provinceAndCityData,
  osshost,
  pageSize,
  getQuerySize,
  qrcode,
  imgUrlFilter,
  forinCopy,
  copy,
  majorHtmlBoxH,
  dataReset,
  fprice,
  checkUserAuth,
  imageBase64ToBlob,
  elMessageTip,
  parseQuery,
  fDateZone,
  fDate,
  formatTime,
  get7Day,
  previewLoading,
  previewSetUp,
  baseMsg,
  resMsg,
  download,
  ParseData,
  ReqApi,
  LocationHref
};
